mod chat_service;

use std::borrow::BorrowMut;
use protobuf::Message;
use socket::{connect_to, default_acceptHandler, listen_port_on_tcp, Client, Server, TcpClient, TcpServer, default_server_msg_for_client};
use std::io::{Read, Write};
use std::net::{IpAddr, SocketAddr, TcpListener, TcpStream, ToSocketAddrs};
use std::str::FromStr;
use std::sync::mpsc::{channel, sync_channel, Sender};
use std::thread;
use std::time::Duration;
use crate::chat_service::{EchoRequest, EchoResponse};

fn main() {
    let port = Some(9999u16);
    // 创建 tcp_server
    let mut tcp_server = TcpServer::new(port, Some(&"127.0.0.1")).unwrap();
    // 设置accept handler
    tcp_server.setAcceptHandler(default_acceptHandler);
    // 启动
    let result = tcp_server.start();
    if result.is_ok() {
        let mut client = TcpClient::new();
        // 设置处理stream的handler
        client.set_stream_handler(default_server_msg_for_client);

        if client.connect("127.0.0.1:9999".to_string()).is_ok() {
            let stream = client.get_stream("127.0.0.1:9999", None).unwrap();
            // handle tcpStream
            let mut msg = EchoRequest::new();
            msg.set_message("hello, i am client!".to_string());
            assert!(stream.write(&msg.write_to_bytes().unwrap()).is_ok());
        }
    }

    // 防止主线程结束
    thread::sleep(Duration::from_secs(5));
}

fn communicate_with_channel() {
    let (tx, rx) = channel();
    let port = Some(9999);
    let addr = IpAddr::from_str("127.0.0.1").unwrap();
    let tcp_listener = listen_port_on_tcp(port, addr).unwrap();
    let handle = thread::spawn(move || match tcp_listener.accept() {
        Ok((mut stream, _)) => {
            let mut buff = [0; 128];
            let size = stream.read(&mut buff).unwrap();
            println!("server receive size:{}", size as i32);
            println!(
                "msg:{}",
                String::from_utf8_lossy(&mut buff[..size]).to_lowercase()
            );
        }

        Err(e) => (println!("occour err:{}", e)),
    });
    tx.send(true).unwrap();

    // create new thread for client
    // receive msg from sender
    thread::spawn(move || {
        if rx.recv().unwrap() {
            connect_to(SocketAddr::new(addr, port.unwrap()));
        }
    });

    handle.join().unwrap();
}
